package com.example.audiobooks.play.fragment;

import static android.content.Context.BIND_AUTO_CREATE;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.audiobooks.R;

import com.example.audiobooks.base.BaseFragment;

import org.json.JSONArray;


public class PlayFragment extends BaseFragment {

    private String TAG = "PlayFragment";
    private View view;
    private ImageView iv_disk; // 光盘（设置动画）
    private static SeekBar musicProgressBar; // 进度条
    private static TextView currentTv; // 当前音乐播放时长
    private static TextView totalTv; // 当前音乐总时长
    private Button quit_btn;    //退出应用（关闭音乐）
    private Button mPlayPattern, mPlayLast, btn_play, mPlayNext, mPlayMenu; // 5个控制按钮
    private ObjectAnimator animator;
    private MusicPlayerServices.MusicControl control;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            control = (MusicPlayerServices.MusicControl) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    ;


    //以下是绑定界面使用
    public TextView mMusicName;  //显示歌曲名称
    public TextView mMusicArtist;  //显示演唱者

    private String account;    //账户
    public int musicId;   //歌曲id
    public int songNum = 0;  //歌曲总数
    private int play_key;   //播放的状态
    private int play_currentTv; //记录播放的位置
    public static int currentPostition;


    public static JSONArray sMusicList;  //存储歌曲信息

    //初始化界面
    public View initView() {
        view = View.inflate(mContext, R.layout.fragment_play, null);
        init();
        SharedPreferences preferences = this.getActivity().getSharedPreferences("data", 0);
        play_key = preferences.getInt("play_key", 0);
        Log.e("TAG", "initView: 获得状态+" + play_key + "播放时间" + play_currentTv);
        return view;
    }

    public void init() {
        iv_disk = view.findViewById(R.id.iv_music); //显示歌曲图片
        musicProgressBar = view.findViewById(R.id.sb);
        currentTv = view.findViewById(R.id.tv_progress);
        totalTv = view.findViewById(R.id.tv_total);
        btn_play = view.findViewById(R.id.btn_play);    //播放按钮
        mPlayPattern = view.findViewById(R.id.play_way_btn);

        /*btn_pause = view.findViewById(R.id.btn_pause);
        btn_continue = view.findViewById(R.id.btn_continue_play);*/
        quit_btn = view.findViewById(R.id.quit_btn);

        OnClick onClick = new OnClick();
        btn_play.setOnClickListener(onClick);
       /* btn_pause.setOnClickListener(onClick);
        btn_continue.setOnClickListener(onClick);*/
        quit_btn.setOnClickListener(onClick);
    }


    @Override
    public void initData() {
        super.initData();
        Guangpang();    //光盘动效；
    }

    class OnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_play:
                    switch (play_key) {
                        case 0:
                            //第一次播放
                            btn_play.setBackgroundResource(R.drawable.bofangb);

                            // 播放音乐
                            control.play();
                            // 光盘开始转动
                            animator.start();
                            play_key = 1;
                            break;
                        case 1:
                            //暂停播放
                            btn_play.setBackgroundResource(R.drawable.bofang);
                            control.pause();
                            // 光盘暂停
                            animator.pause();
                            play_key = 2;
                            play_currentTv = currentPostition -3000;    //提前3秒
                            Log.d(TAG, "onDestroy: " + play_currentTv);
                            if (play_currentTv != 0) {
                                SharedPreferences.Editor editor = getActivity().getSharedPreferences("data", 0).edit();
                                //MODE_PRIVATE 也可以用 0
                                editor.putInt("play_currentTv", play_currentTv);
                                editor.apply();
                            }
                            break;
                        case 2:
                            //继续播放
                            btn_play.setBackgroundResource(R.drawable.bofangb);
                            control.resume();
                            // 光盘继续转动
                            animator.resume();
                            play_key = 1;
                            break;
                        default:
                            break;
                    }
                    break;

                case R.id.quit_btn:
                    getActivity().finish();
                    // 退出应用
                    break;
            }
        }
    }


    @Override
    public void onDestroy() {
        control.stop();

        getActivity().unbindService(conn);
        super.onDestroy();
    }

    // 获取从MusicPlayerServices传递过来的消息
    public static Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData(); //获取从子线程发送过来的音乐播放进度
            int duration = bundle.getInt("duration");                  //歌曲的总时长
            currentPostition = bundle.getInt("currentPosition");//歌曲当前进度
            musicProgressBar.setMax(duration);                //设置SeekBar的最大值为歌曲总时长
            musicProgressBar.setProgress(currentPostition);//设置SeekBar当前的进度位置
            String totalTime = msToMinSec(duration); // 歌曲总时长
            String currentTime = msToMinSec(currentPostition); // 歌曲当前播放时长
            totalTv.setText(totalTime);
            currentTv.setText(currentTime);
        }
    };

    public static String msToMinSec(int ms) {
        int sec = ms / 1000;
        int min = sec / 60;
        sec -= min * 60;
        return String.format("%02d:%02d", min, sec);
    }

    public void Guangpang() {
        animator = ObjectAnimator.ofFloat(iv_disk, "rotation", 0, 360.0F); // 对象是iv_disk，动作是rotation旋转，角度从0到360度，这里用的是浮点数，所以要加个F
        animator.setDuration(10000); // 这是设置动画的时长，单位为毫秒，这里设置了10秒转一圈
        animator.setInterpolator(new LinearInterpolator()); // 旋转时间函数为线性，意为匀速旋转
        animator.setRepeatCount(-1); // 设置转动圈数，-1为一直转动

        Intent intent = new Intent(getActivity(), MusicPlayerServices.class);
        getActivity().bindService(intent, conn, BIND_AUTO_CREATE);


        musicProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当音乐停止后，停止光盘动画
                if (progress == seekBar.getMax()) {
                    animator.pause();
                    btn_play.setBackgroundResource(R.drawable.bofang);
                }
                if (fromUser) { // 判断是不是用户拖动的
                    control.seekTo(progress);
                    btn_play.setBackgroundResource(R.drawable.bofangb);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                control.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                control.resume();

            }
        });
    }

}


